<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;

class UserController extends Controller
{
    //
    public function index(Request $request)
    {
        $user=User::query()
        ->orderBy('id','desc')
        ->paginate($request->input('per_page',10));

        return response()->json([
            'code'=>200,
            'msg'=>'success',
            'data'=>$user
        ]);
    }

    public function login(Request $request){

        $request->validate([
            'name'=>'required',
            'password'=>'required'
        ]);

        $user=User::Where('name',$request->name)->first();

        if(!$user){
            throw ValidationException::withMessages([
                'name'=>'用户名不存在'
            ]);
        }
      
        if(!password_verify($request->password,$user->password)){
            throw ValidationException::withMessages([
                'password'=>'密码错误'
            ]);
        }
        return response()->json([
            'code'=>200,
            'msg'=>'success',
            'data'=>$user
        ]);
    }
}
